package com.example.findtherinbow.utils;


import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;

public class DrawableToJsonUtil {

    public static String drawableToJson(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        // 将 Drawable 转换为 Bitmap
        Bitmap bitmap = drawableToBitmap(drawable);

        // 将 Bitmap 转换为 Base64 编码的字符串
        String base64String = bitmapToBase64(bitmap);

        // 创建 JSON 对象并存储 Base64 字符串
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("image", base64String);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 将 JSON 对象转换为字符串
        return jsonObject.toString();
    }

    private static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        // 其他类型的 Drawable 转换为 Bitmap
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        return bitmap;
    }

    private static String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        byte[] byteArray = outputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
}

